// const jwt = require('jsonwebtoken')
const jwt = require('../../middleware/jwt/jwt')
// , koajwt = require('koa-jwt');
// 验证函数

// token权限拦截
// app.use(koajwt({
//     secret: 'anlin'
// }).unless({
//     path: [/\/sign/]
// }));


const util = require('../../util/index.js')
const { User } = require('../../router/schema')

module.exports = (app) => {
  app.use(async (ctx, next) => {
    if (ctx.request.url.match('sign')) {
      await next()
    } else if (ctx.request.url.includes('.')) {
      await next()
    } else {
      const authorization = ctx.request.header.authorization;
      if (authorization) {
        const verFlog = util.checkUndefined([
          {
            token: authorization,
            type: 'string',
            label: 'token'
          }
        ]);
        if (verFlog) {
          const token = authorization.split(' ')[1]
          const result = await jwt.verify(token.split('.')[0])
          if (result) {
            jwt.expire('token' + result.split('.')[0],util.tokenTime)
            const yz = async (num) => {
              const _id = result.split('.')[1];
              await User.findOne({ _id }).then(async res => {
                if (res) {
                  if (res.role === num) {
                    await next()
                  } else {
                    ctx.body = util.back(-201)
                  }
                } else {
                  ctx.body = util.back(-201)
                }
              })
            }
            if (ctx.request.url.match('admin')) {
              await yz(100)
            } else {
              await yz(10)
            }
          } else {
            return ctx.body = util.back(-201)
          }
        } else {
          ctx.body = util.back(-201)
        }
      } else {
        ctx.body = util.back(-201)
      }
    }
  })
}